package com.luge.model.request;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.luge.utils.Helper;

public class Request {
	private Task task;
	private RequestCallBack callBack;
	private Handler handler;
	private Context context;

	public Request(Task task, RequestCallBack callBack) {
		this.task = task;
		this.callBack = callBack;
	}

	public Request(Context context, Task task, RequestCallBack callBack) {
		this.task = task;
		this.callBack = callBack;
		this.context = context;
	}

	public void start() {
		if (context != null) {
			Helper.showDialog(context);
		}
		handler = new Handler(new Handler.Callback() {
			@Override
			public boolean handleMessage(Message msg) {
				Helper.removeDialog();
				BaseModel model = (BaseModel) msg.obj;
				if (model == null) {
					callBack.fail("");
				} else if (model.getCode() == 0) {
					callBack.fail(model.getErrorInfo());
				} else {
					callBack.success(model);
				}
				return false;
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				Message msg = new Message();
				msg.obj = ParseJSON.request(task);
				handler.sendMessage(msg);
			}
		}).start();
	}

	public interface RequestCallBack {
		void success(Object object);

		void fail(String error);
	}
}
